package com.jinxiangyang.utils.handler;

import com.alibaba.fastjson2.JSON;
import com.jinxiangyang.domain.LoginUser;
import com.jinxiangyang.utils.ServletUtils;
import com.jinxiangyang.utils.config.RedisCache;
import com.jinxiangyang.utils.constants.CacheConstants;
import com.jinxiangyang.utils.constants.Constants;
import com.jinxiangyang.utils.result.AjaxResult;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义退出处理类 返回成功
 *
 * @author ruoyi
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler
{

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;
    @Autowired
    private RedisCache redisCache;
    /**
     * 退出处理
     *
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException
    {
        //获取token
        String token = request.getHeader("token");
        Claims claims = parseToken(token);
        // 解析对应的权限以及用户信息
        String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
        String userKey = getTokenKey(uuid);
        LoginUser user = redisCache.getCacheObject(userKey);
        if(user == null){
            throw new IllegalStateException("token is error");
        }
        redisCache.deleteObject(userKey);
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.success("退出成功")));
    }
    private String getTokenKey(String uuid)
    {
        return CacheConstants.LOGIN_TOKEN_KEY + uuid;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token)
    {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

}
